const express = require("express")
const router=express.Router()
const {comMysql}=require("../../mysql")
const passport = require("passport")
const mysql = require("../../mysql")


router.get("/test",(req,res)=>{
  res.send("test")
})
//添加
router.post("/add",passport.authenticate("jwt",{session:false}),async (req,res)=>{
  const profileFields={}
  if(req.body.type) profileFields.type=req.body.type
  if(req.body.descript) profileFields.descript=req.body.descript
  if(req.body.income) profileFields.income=req.body.income
  if(req.body.cash) profileFields.cash=req.body.cash
  if(req.body.remark) profileFields.remark=req.body.remark
  if(req.body.date) profileFields.date=req.body.date
  if(req.body.expend) profileFields.expend=req.body.expend
  let sql=`insert into profile (type,descript,income,cash,remark,date,expend) values (?,?,?,?,?,?,?)`
  let arr=[profileFields.type,profileFields.descript,profileFields.income,profileFields.cash,profileFields.remark,profileFields.date,profileFields.expend]
  console.log(arr);
  
  let data=await comMysql(sql,arr)
  if(data){
    res.json(profileFields)
  }
}) 
//获取全部信息
router.get("/",passport.authenticate("jwt",{session:false}),async (req,res)=>{
  let sql=`select * from profile`

  const data=await comMysql(sql)
  if(data.length<0){
    return res.status(404).json({msg:"没有查到哦"})
  }
  return res.json(data)
})
//获取单个
router.get("/:id",passport.authenticate("jwt",{session:false}),async (req,res)=>{
  let sql=`select * from profile where id = ?`
  let arr=[req.params.id]

  const data=await comMysql(sql,arr)
  if(data.length<0){
    return res.status(404).json({msg:"没有查到哦"})
  }
  return res.json(data)
})
//编辑
router.post("/edit/:id",passport.authenticate("jwt",{session:false}),async (req,res)=>{
  const profileFields={}
  if(req.body.type) profileFields.type=req.body.type
  if(req.body.descript) profileFields.descript=req.body.descript
  if(req.body.income) profileFields.income=req.body.income
  if(req.body.cash) profileFields.cash=req.body.cash
  if(req.body.remark) profileFields.remark=req.body.remark
  if(req.body.date) profileFields.date=req.body.date
  if(req.body.expend) profileFields.expend=req.body.expend
  let sql=`update profile set type=?,descript=?,income=?,cash=?,remark=?,date=?,expend=? where id =?`
  let arr=[profileFields.type,profileFields.descript,profileFields.income,profileFields.cash,profileFields.remark,profileFields.date,profileFields.expend,req.params.id]
  console.log(arr);
  
  let data=await comMysql(sql,arr)
  if(data){
    res.json(profileFields)
  }
}) 
//删除
router.get("/del/:id",passport.authenticate("jwt",{session:false}),async (req,res)=>{
  let sql=`delete from profile where id = ?`
  let arr=[req.params.id]

  const data=await comMysql(sql,arr)
  if(data.length<0){
    return res.status(404).json({msg:"没有数据哦"})
  }
  return res.json(data)
})

module.exports=router